<template>
  <a-card title="编辑房户信息" style="width: 600px;pointer-events: all;">
    <template #extra>
      <a-select ref="select" v-model:value="selectBuild" style="width: 120px" :options="buildsOption"
        @change="handleChange"></a-select>
    </template>
    <a-table size="small" bordered :data-source="houseList" :loading="loading" :columns="buildingColumns"
      :pagination="pagination" @change="handlePaginationChange">
      <template #bodyCell="{ column, text, record }">
        <template v-if="['doorNumText', 'floorNumText', 'numberText'].includes(column.dataIndex)">
          <a-tag :color="column.dataIndex === 'doorNumText' ? 'red' : 'green'">{{ text }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a @click="edit(record)">编辑信息</a>
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'positionFix'">
          <div @click="focusOnArea(record)">
            <img style="cursor: pointer;" width="20" height="20" src="/src/assets/position.png" alt="">
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <FormInfo :formData="formData" :formOpen="formOpen" @onClose="onClose" />
</template>

<script setup>
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
import { getBuild, getHouse, getOneHouseInfo } from '../api/api'
import { ref, onMounted, reactive, onBeforeUnmount } from 'vue'
import FormInfo from './FormInfo.vue'
import { useMapData } from '@/store'
import { destination } from '@turf/turf'

const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const selectBuild = ref('')
// 楼栋列表
const buildsOption = ref([])
// 提交的表单信息
const formData = ref({})
// 外部组件控制表单显隐
const formOpen = ref(false)
const loading = ref(false)
// 选中的楼栋
const currentBuild = ref(null)
const pagination = reactive({
  total: 0,
  current: 0,
  pageSize: 0
})
const buildingColumns = ref([
  {
    title: '门牌号',
    dataIndex: 'doorNumText',
    align: 'center',
    ellipsis: true
  }, {
    title: '单元号',
    dataIndex: 'numberText',
    align: 'center',
    ellipsis: true
  }, {
    title: '楼层',
    dataIndex: 'floorNumText',
    align: 'center',
    ellipsis: true
  }, {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    ellipsis: true
  }, {
    title: '定位',
    dataIndex: 'positionFix',
    align: 'center',
    width: '10%'
  }
])

// 楼栋信息
const houseList = ref([])
// 当前渲染的图元
let primitiveHouse
let currentBuildEnt

// 渲染下拉列表
onMounted(async () => {
  const buildInfo = await getBuild()
  if (buildInfo.code === 200) {
    buildsOption.value = buildInfo.data.map(item => {
      return {
        label: item.name,
        value: item.id,
        polygon: item.polygon
      }
    })
  }
})

// 通过接口，查询表格
const getHouseData = async (queryParam) => {
  const res = await getHouse(queryParam)
  if (res.code === 200) {
    const { data: { list, total } } = res
    houseList.value = list.map(item => {
      const { floorNum, number } = item
      return {
        ...item,
        doorNumText: `${floorNum}-0${number}`,
        numberText: `${number}单元`,
        floorNumText: `${floorNum}楼`
      }
    })
    pagination.total = total
    pagination.current = queryParam.pageIndex
    pagination.pageSize = houseList.value.length
    console.log(houseList.value);
  }
}

// 切换楼栋，需要渲染出当前所在的楼栋范围，然后渲染表格
const handleChange = (e) => {
  const target = buildsOption.value.find(item => item.value === e)
  if (target) {
    // 获取到楼栋的多边形范围
    const { polygon, label } = target
    // 得到多边形中心点，让视角跳转过去
    const center = turf.center(polygon)
    const coordinates = polygon.coordinates[0].reduce((a, b) => a.concat(b), [])
    const cartesian = new Cesium.Cartesian3.fromDegreesArray(coordinates)
    // 渲染多边形
    currentBuildEnt = viewer.entities.add({
      name: label,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(cartesian),
        material: Cesium.Color.RED.withAlpha(0.7),
        classificationType: Cesium.ClassificationType.BOTH
      }
    })
    // 将视角飞跃到模型中心
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        ...center.geometry.coordinates,
        300
      )
    })

    const queryParam = {
      id: e,
      pageIndex: 1
    }
    getHouseData(queryParam)
  }
}

// 显示选中的用户
const focusOnArea = (record) => {
  if (record) {
    // 每次将之前渲染的primitive清除
    primitiveHouse && viewer.scene.primitives.remove(primitiveHouse)
    primitiveHouse=null
    const { polygon, minHeight, maxHeight } = record
    const coordinates=polygon.coordinates[0].reduce((a,b)=>a.concat(b),[])
    const cartesian=new Cesium.Cartesian3.fromDegreesArray(coordinates)
    const polygonHierarchy=new Cesium.PolygonHierarchy(cartesian)
    const geometryInstance = new Cesium.GeometryInstance({
      geometry: new Cesium.PolygonGeometry({
        polygonHierarchy: polygonHierarchy,
        height:minHeight,
        extrudedHeight:maxHeight
      }),
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.YELLOW.withAlpha(0.6)
        )
      }
    })
    primitiveHouse = new Cesium.ClassificationPrimitive({
      geometryInstances: geometryInstance,
      classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
    })
    viewer.scene.primitives.add(primitiveHouse)
  }
}

const onClose=()=>{
  formOpen.value=false
}

const edit =async (data) => {
  const {id,number,floorNum}=data
  const res=await getOneHouseInfo({id})
  if(res?.code===200){
    formOpen.value=true
    let houseNum = number > 9 ? number : "0" + number;
    const houseAddress =number + "单元" + floorNum + houseNum;
    res.data.houseAddress=houseAddress
    res.data.id=id
    formData.value=res.data
  }
}
</script>
